// pages/exercise/detail/detail.js
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    category_id: '',
    category_name:'',
    list_id: '',
    list_name: '',
    date: util.formatDate(new Date()),
    weight:'',
    frequency:'',
    history_detail_list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      category_id: options.category_id,
      category_name: options.category_name,
      list_id: options.list_id,
      list_name: options.list_name
    });
  },

  // query detail
  queryHistoryDetail() {
    let that = this;
    let app = getApp();
    let global_data = app.globalData;
    console.log("global_data:" + JSON.stringify(global_data));
    const db = wx.cloud.database();
    db.collection('exercise_detail').where({
      _openid: global_data.openId,
      category_id: this.data.category_id,
      list_id: this.data.list_id,
      date: util.formatDate(new Date()),
    }).get({
      success: function(res) {
        console.log("from clound query detail data: " + JSON.stringify(res));
        let history_detail_list =  res.data;
        that.setData({
          history_detail_list: history_detail_list
        });
        console.log("setData:" + JSON.stringify(that.data.history_detail_list));
      },
    })
  },

  // submit detail
  submitExerciseDetail(event) {
    console.log(JSON.stringify(event));
    let that = this;
    wx.showLoading();
    console.log("start add detail from cloud");
    let data = {
      category_id: that.data.category_id,
      category_name: that.data.category_name,
      list_id: that.data.list_id,
      list_name: that.data.list_name,
      date: that.data.date,
      weight: that.data.weight,
      frequency: that.data.frequency,
      c_t:util.formatTime(new Date())
    }
    this.cloudAddDetail(data);
  },

  cloudAddDetail(data) {
    const db = wx.cloud.database();
    db.collection('exercise_detail').add({
      // data 字段表示需新增的 JSON 数据
      data: data,
      success: function(res) {
        console.log("from clound add detail data: " + JSON.stringify(res));
        wx.hideLoading();
        wx.navigateBack({
          delta: 1,
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // query history detail
    this.queryHistoryDetail();
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})